import os
import machine
import serial
from machine import Pin
class uart:
    def __init__(self, tx=33, rx=3, Inverse=False, buffSize=512):
        self.port = serial.new(tx, rx, Inverse, buffSize)
    def __del__(self):
        serial.delet(self.port)
    def any(self):
        return serial.any(self.port)
    def open(self, baudRate):
        return serial.open(self.port, baudRate)
    def stop(self):
        return serial.stop(self.port)
    def write(self, ubytes):
        for byte in ubytes:
            serial.write(self.port, byte)
    def read(self):
        return serial.read(self.port)

class BUTTON:
  def __init__(self):
    self.key_event=0
    self.key_state=0
    self.key = Pin(3, Pin.IN, Pin.PULL_UP)
    self.uart = uart(33, 3, False, 512)
    self.uart.open(115200)

  def state(self):
      if self.uart.any():
        ch=self.uart.read()
        print("ch=",ch)
        if ch>0:
            self.key_state +=1
            if self.key_state >=2:
                self.key_state=0
                if "main.py" in os.listdir('/'):
                    os.remove("main.py")
                self.uart.__del__()
                machine.reset()     
      if self.key.value() == 0:
         return 1
      else : return 0
  def event(self):
      if self.uart.any():
        ch=self.uart.read()
        print("ch=",ch)
        if ch>0:
            self.key_state +=1
            if self.key_state >=2:
                self.key_state=0
                if "main.py" in os.listdir('/'):
                    os.remove("main.py")
                self.uart.__del__()
                machine.reset()     
      if (self.key_state == 0):
        if (self.key.value() == 0):
            self.key_state = self.key_state + 1
      elif (self.key_state < 2):
        self.key_state = self.key_state + 1
      elif (self.key_state == 2):
        self.key_state = self.key_state + 1
        self.key_event = 1
      else:
        if (self.key.value() == 1):
          self.key_state = 0
      return self.key_event 
